public without sharing class CaseHandler implements Triggers.Handler
{
   public Map<Id,Set<Id>> shareMap = new Map<Id,Set<Id>>();
    public void handle() {
        Set<Id> cIdSet = new Set<Id>();
        Map<Id,String> errorMap = new Map<Id,String>();
        // Set<String> strSet = new Set<String>();
        Map<Id,Case> cMap = new Map<Id,Case>();

        //部门列表-区域列表
        List<String> deptList = new List<String>();
        // List<String> areaList = new List<String>();
        //专家ID
        Map<String,String> userMap = new Map<String,String>();

        // Case oldc = new Case();
        Map<Id,Case> oldMap = new Map<Id,Case>();
        List<Case> newCaseList = (List<Case>)Trigger.new;
        if(Trigger.isUpdate){
            oldMap = (Map<Id,Case>)Trigger.oldMap;
        }

        //插入组长和设置Case部门
        if(Trigger.isBefore){
            Map<String,String> deptMap = new Map<String,String>();
            deptMap.put('工程', '客户服务中心(工程部)');
             deptMap.put('应用', '客户服务中心(产品培训部)');
            for(Case c : newCaseList){
                Case old  = oldMap == null  ?  null : oldMap.get(c.Id );
                if(old == null) old = new Case();
                if(c.Servicetype__c != null && old.Servicetype__c != c.Servicetype__c  )c.CaseDepartment__c = deptMap.get( c.Servicetype__c );
                
                

            }

           /* for(Case c : newCaseList){
                //记录专家ID
               
                if(!String.isBlank(c.User__c)){
                    if(!userMap.containsKey(c.User__c)){
                        userMap.put(c.User__c,'');
                    }
                }
            }

            if(userMap.size() > 0){
                List<User> ul = [SELECT Id, UserDepartment__c FROM User WHERE Id IN :userMap.keySet()];
                if(ul != null && ul.size() >0){
                    userMap.clear();
                    for(User u : ul){
                        if(!userMap.containsKey(u.Id)){
                            userMap.put(u.Id, u.UserDepartment__c);
                        }
                    }
                }
            }
            //设置Case部门
            for(Case c : newCaseList){
                if(!String.isBlank(c.User__c) && userMap.containsKey(c.User__c)){
                    c.CaseDepartment__c = userMap.get(c.User__c);
                }

            }
            */


           /*for(Case c : newCaseList){
                Case oldc = oldMap.get(c.Id);
                // 根据部门区域产品线去选择组长
                //个案的部门=工程，区域=四川一区，产品线=生化，找到用户（区域=工程四川一区，是否组长打钩）
                if (null != c.CaseDepartment__c && null != c.ProductLine__c && null != c.District__c){
                    if(Trigger.isInsert || Trigger.isUpdate && 
                        (c.CaseDepartment__c != oldc.CaseDepartment__c || c.ProductLine__c != oldc.ProductLine__c || c.District__c != oldc.District__c)) {
                            c.DepZonePro__c = c.CaseDepartment__c + c.District__c;
                            // strSet.add(c.DepZonePro__c);
                            cMap.put(c.Id,c);
                            deptList.add(c.CaseDepartment__c);
                            // areaList.add(c.District__c);
                    }
                }
            }*/

        }

       /* if(!deptList.isEmpty()){
            List<User> ulist = [
                    SELECT Id, ProductLine__c, UserDepartment__c, Area__c, Area2__c, ManagerId, Manager.ManagerId ,ActingGroupLeader__c
                    FROM User 
                    WHERE UserDepartment__c IN :deptList 
                    // AND Area__c IN :areaList
                    AND IsTeamLeader__c = true];

            System.debug('ulist: '+ulist) ;     
            for(Id cid : cMap.keySet()){
                Case c = cmap.get(cid);
                if(String.isNotBlank(c.ProductLine__c)){
                    for (User u : ulist) {
                        if(String.isNotBlank(u.ProductLine__c) && u.ProductLine__c.contains(c.ProductLine__c)){
                            
                            if(u.UserDepartment__c == c.CaseDepartment__c && (u.Area__c == c.District__c || !String.isBlank(u.Area2__c) && u.Area2__c.contains(c.District__c))){
                                c.User__c = u.ActingGroupLeader__c == null ? u.Id:u.ActingGroupLeader__c;
                                c.Manager__c = u.ManagerId;
                                c.Director__c = u.Manager.ManagerId;
                                break;
                            }else{
                                c.User__c = null;
                                c.Manager__c = null;
                                c.Director__c = null;
                                errorMap.put(c.Id, '不存在用户！');
                            }
                        }else{
                            c.User__c = null;
                            c.Manager__c = null;
                            c.Director__c = null;
                            errorMap.put(c.Id, '不存在用户！');
                        }
                    }                
                }else{
                    c.User__c = null;
                    c.Manager__c = null;
                    c.Director__c = null;
                    errorMap.put(c.Id, '不存在用户！');
                }
            }
        } 
        */       

        //是否共享
        if(Trigger.isAfter){
            for(Case c : newCaseList){
                Case oldc = oldMap.get(c.Id);

                System.debug('CaseHandler==>'+c );
                System.debug(c.OwnerId);
                System.debug(oldc);
                System.debug((Trigger.isInsert || Trigger.isUpdate && c.User__c != oldc.User__c) == true );
               /* if (null != c.Professional__c && c.Professional__c != c.OwnerId)
                {
                    if(Trigger.isInsert || Trigger.isUpdate && c.Professional__c != oldc.Professional__c) {
                        judgeShareMap(c.Id,c.Professional__c);
                    }
                }*/
                if (null != c.Engineer__c &&  c.Engineer__c != c.OwnerId)
                {
                    if(Trigger.isInsert || Trigger.isUpdate && c.Engineer__c != oldc.Engineer__c) {
                        judgeShareMap(c.Id,c.Engineer__c);
                    }
                }
                if (null != c.User__c &&  c.User__c != c.OwnerId)
                {
                    if(Trigger.isInsert || Trigger.isUpdate && c.User__c != oldc.User__c) {
                        judgeShareMap(c.Id,c.User__c);
                    }
                }

                if (errorMap.containsKey(c.Id)){
                    c.addError(errorMap.get(c.Id));
                }
            }
        System.debug('shareMap==>'+shareMap);

            if(!shareMap.isEmpty()){
                //共享操作！
                System.debug('@shareMap: '+shareMap);
                shareTo();
            }
        }

        if(Trigger.isAfter && Trigger.isUpdate)
        {
            // Map<Id,Case> coldMap = (Map<Id,Case>)Trigger.oldMap;
            for (Case c : (List<Case>)Trigger.new) 
            {
                Case oldc = oldMap.get(c.Id);
                if(c.Status == '关闭'  && c.Status != oldc.Status)   //个案关闭将之前所共享的人改为只读
                {
                    cIdSet.add(c.Id);
                }
            }
        }

        //关闭个案时，取消共享。
        if(!cIdSet.isEmpty())
        {
            List<Caseshare> csList = [select Id, CaseAccessLevel, RowCause from Caseshare where CaseId in: cIdSet];
            System.debug(csList);
            List<Caseshare> upcsList = new List<Caseshare>();
            for(Caseshare cs : csList)
            {
                //if(cs.CaseAccessLevel !='All') //不是个案所有人
                if(cs.RowCause == 'Manual')
                {
                    cs.CaseAccessLevel = 'Read';
                    upcsList.add(cs);
                }
            }
            if(!upcsList.isEmpty()){
                System.debug(upcsList);
                update upcsList;
            }           
        }
    }

    public void judgeShareMap( Id cid,Id sid)
    {   

        System.debug('judgeShareMap');
        Set<Id> aSet  = shareMap.containsKey(cid) ? shareMap.get(cid) : new Set<Id>();
        aSet.add(sid);
        shareMap.put(cid,aSet);

    }

    public  void shareTo()
    {
        //System.debug('this is future ： '+shareMap);
        List<Caseshare> csList = new List<Caseshare>();
        for(Id cid : shareMap.keySet())
        {
            Set<Id> sidSet = shareMap.get(cid);
            for(Id uid : sidSet)
            {
                Caseshare ashare = new Caseshare();
                ashare.CaseAccessLevel = 'Edit';
                ashare.CaseId = cid;
                ashare.UserOrGroupId = uid;
                csList.add(ashare);
            }
        }
        if(!csList.isEmpty())
        {
            System.debug('@共享insert : '+ csList);
            insert csList;
            System.debug('@afterinsert : '+ csList);
        }
        shareMap.clear();
    }

}